$(function () {

    //工具栏搜索框快速查询
    $("#saleChance-search").searchbox({
        searcher : function () {
            //获取快速搜索的类型
            var searchName = $('#saleChance-search').searchbox('getName');
            //获取搜索框的值
            var searchVal = $('#saleChance-search').searchbox('getValue');
            if (searchName == 'chanceTheme') {
                clearDataGrid();
                $('#zjk-saleChance-dg').datagrid({
                    queryParams:null
                });
                $('#zjk-saleChance-dg').datagrid({
                    url : 'find-all-sale-chance',
                    method : 'post',
                    queryParams : {
                        chanceTheme : searchVal
                    }
                });

                $('#zjk-saleChance-dg').datagrid('reload');
            }else if (searchName == 'stage'){
                clearDataGrid();
                $('#zjk-saleChance-dg').datagrid({
                    queryParams:null
                });
                $('#zjk-saleChance-dg').datagrid({
                    url : 'find-all-sale-chance',
                    method : 'post',
                    queryParams : {
                        stage : searchVal
                    }
                });

                $('#zjk-saleChance-dg').datagrid('reload');

            } else if(searchName == 'type'){
                clearDataGrid();
                $('#zjk-saleChance-dg').datagrid({
                    queryParams:null
                });
                $('#zjk-saleChance-dg').datagrid({
                    url : 'find-all-sale-chance',
                    method : 'post',
                    queryParams : {
                        type : searchVal
                    }
                });

                $('#zjk-saleChance-dg').datagrid('reload');

            }else if(searchName == 'state'){
                clearDataGrid();
                $('#zjk-saleChance-dg').datagrid({
                    queryParams:null
                });
                $('#zjk-saleChance-dg').datagrid({
                    url : 'find-all-sale-chance',
                    method : 'post',
                    queryParams : {
                        state : searchVal
                    }
                });

                $('#zjk-saleChance-dg').datagrid('reload');

            }


        }

    });

    //点击工具栏的“查询所有”按钮，查询所有销售机会
    $("#zjk-search-all-saleChance-btn").linkbutton({
        onClick:function () {
            $('#zjk-saleChance-dg').datagrid({
                queryParams : null
            });
            $('#zjk-saleChance-dg').datagrid({
                url : 'find-all-sale-chance',
                method : 'post',
                queryParams : {
                    stage : null
                },
            });
            $('#zjk-saleChance-dg').datagrid('reload');
            $("#saleChance-search").searchbox('setValue',null);
        }
    });


    //高级查询
    //点击高级查询按钮，显示高级查询框
    $("#advance-search-btn").linkbutton({
        onClick: function () {
            $('#advance-sale-chance-dialog').dialog({
                onLoad: function () {
                    $("#zjk-advance-saleChance-client").combobox({
                        url: 'saling/getClientInfoList',
                        method: 'post',
                        valueField: 'cid',
                        textField: 'cname',
                        panelHeight: 'auto',
                        onSelect: function (record) {
                            var url = "saling/loadContactInformation";
                            $("#zjk-advance-saleChance-contact").combobox({
                                url: url,
                                method: 'post',
                                queryParams: {'cid': record.cid},
                                valueField: 'contactid',
                                textField: 'contactName'
                            });

                        }
                    });
                }
            });
            $('#advance-sale-chance-dialog').dialog('open');
        },

    })
    ;
    //点击最下方的查询按钮，dialog关闭，提交表单，表格刷新
    $("#saleChance-advance-search-btn2").linkbutton({
        onClick:function () {

            clearDataGrid();
            $('#saleChance-advance-search-form').form({
                success:function (e) {
                    $('#zjk-saleChance-dg').datagrid({
                        queryParams : null
                    });
                    $('#zjk-saleChance-dg').datagrid({
                        url : 'advance-sale-chance',
                        method : 'post',
                        queryParams :{
                            chanceTheme:$("#saleChance-advance-search-form input[name=chanceTheme]").val(),
                            stage:$("#saleChance-advance-search-form input[name='stage']:checked").val(),
                            state:$("#saleChance-advance-search-form input[name='state']:checked").val(),
                            minDay:$("#saleChance-advance-search-form input[name=minDay]").val(),
                            maxDay:$("#saleChance-advance-search-form input[name=maxDay]").val(),
                            type:$("#saleChance-advance-search-form input[name=type]").val(),
                            //客户
                            clientId:$("#saleChance-advance-search-form input[name=clientId]").val(),
                            //客户联系人
                            contactId:$("#saleChance-advance-search-form input[name=contactId]").val(),
                            createStartTime : $("#saleChance-advance-search-form input[name=createStartTime]").val(),
                            createEndTime : $("#saleChance-advance-search-form input[name=createEndTime]").val(),
                            userId:$("#saleChance-advance-search-form input[name=userId]").val(),
                            minMoney:$("#saleChance-advance-search-form input[name=minMoney]").val(),
                            maxMoney:$("#saleChance-advance-search-form input[name=maxMoney]").val(),
                            asterisk:$("#saleChance-advance-search-form input[name='asterisk']:checked").val(),
                            priority:$("#saleChance-advance-search-form input[name='priority']:checked").val(),
                            expectStartTime:$("#saleChance-advance-search-form input[name=expectStartTime]").val(),
                            expectEndTime:$("#saleChance-advance-search-form input[name=expectEndTime]").val(),
                            intentRpoduct:$("#saleChance-advance-search-form input[name=intentRpoduct]").val(),
                            succedaneum:$("#saleChance-advance-search-form input[name=succedaneum]").val(),
                            outlineNeed:$("#saleChance-advance-search-form input[name=outlineNeed]").val(),
                            remarks:$("#saleChance-advance-search-form input[name=remarks]").val(),
                            updateStartTime : $("#saleChance-advance-search-form input[name=updateStartTime]").val(),
                            updateEndTime : $("#saleChance-advance-search-form input[name=updateEndTime]").val()

                        }
                    });
                }
            }).submit();
            $('#advance-sale-chance-dialog').dialog('close');

        }});
    //点击“返回快速查询”高级查询框隐藏
    $("#saleChance-advance-search-btn").linkbutton({onClick:function () {
            $('#advance-sale-chance-dialog').dialog('close');
        }});

    //工具栏删除按钮事件
    $("#zjk-delete-saleChance-btn").linkbutton({
        onClick: function () {
            var rows = $('#zjk-saleChance-dg').datagrid('getChecked');
            if (rows.length == 0) {
                $.messager.alert("提示", "请先选择要删除的行！");
            } else {
                $.messager.confirm("询问", "您确定要删除吗？", function (v) {
                    if (v) {
                        for (var i = 0; i < rows.length; i++) {
                            if (rows[i]) {
                                var id = rows[i].chId;
                                $.post('deleteSaleChance', {chId: id}, function (r) {
                                    if (r.success) {
                                        $('#zjk-saleChance-dg').datagrid('reload');
                                    } else {
                                        $.messager.alert("提示", r.messager);
                                    }
                                });
                            }
                        }
                    }
                })
            }
        }
    });


    //点击工具栏“新建”按钮事件
    $("#zjk-add-saleChance-open-dialog-btn").linkbutton({
        onClick: function () {

            $('#zjk-add-sale-chance').dialog({
                onLoad: function () {
                    $("#zjk-add-saleChance-client").combobox({
                        url: 'saling/getClientInfoList',
                        method: 'post',
                        valueField: 'cid',
                        textField: 'cname',
                        panelHeight: 'auto',
                        onSelect: function (record) {
                            var url = "saling/loadContactInformation";
                            $("#zjk-add-saleChance-contact").combobox({
                                url: url,
                                method: 'post',
                                panelHeight: 'auto',
                                queryParams: {'cid': record.cid},
                                valueField: 'contactid',
                                textField: 'contactName'
                            });

                        }
                    });
                    $("#zjk-add-saleChance-user").combobox({
                        url: 'saling/getUserInfoList',
                        method: 'post',
                        panelHeight: 'auto',
                        valueField: 'uId',
                        textField: 'uname'
                    });
                }
            });
            $('#zjk-add-sale-chance').dialog('open');
        },

    });
    
    //添加窗口“保存”按钮事件
    $("#zjk-saleChance-add-dialog-bb-save").linkbutton({
        onClick:function () {
            //提交表单事件
            $('#zjk-saleChance-f').form({
                onSubmit:function (parmps) {
                    //表单验证
                    return $(this).form('validate');
                },
                success:function (r) {
                    r = eval('(' + r + ')');
                    if (r.success){
                        $.messager.alert("提示","恭喜，添加成功！");
                        //窗口关闭
                        $('#zjk-add-sale-chance').dialog('close');
                        //刷新展示列表
                        $('#zjk-saleChance-dg').datagrid('reload');
                        //清空表单
                        $('#zjk-saleChance-f').form('clear');

                    }else {
                        $.messager.alert("错误",r.messager);
                    }
                    
                }
            }).submit();
        }
    });


   // 动态添加操作栏图标
    $("#zjk-saleChance-dg").datagrid({
/*        onBeforeLoad:function(){
            //初始化页脚数据
            var datar = $(this).datagrid("getData");
            datar.footer =new Array();
            datar.footer[0]=new Object();
            datar.footer[1]=new Object();
            datar.footer[1].chanceTheme = '∑总金额：';
            datar.footer[1].expectMoney = 0;
            datar.footer[0].chanceTheme = '∑本页金额：';
            datar.footer[0].expectMoney = 0;
            $(this).datagrid('loadData',JSON.parse(JSON.stringify(datar)));
        },*/
        onLoadSuccess: function (data) {

          /*  var total =0;
            var totalAll =0;
            var rows = $("#zjk-saleChance-dg").datagrid('getRows');//获取本页数据
            var allrows =$("#zjk-saleChance-dg").datagrid('getData');//获取所有数据
            alert(JSON.stringify(rows));
            for(var j = 0; j<allrows.total; j++){
                totalAll+=allrows.rows[j]['expectMoney'];
            }
            for (var i = 0; i < rows.length; i++) {
                total += rows[i]['expectMoney'];
            }
            var footerRows = $('#zjk-saleChance-dg').datagrid('getFooterRows');
            footerRows[0]['expectMoney'] = total ;
            footerRows[1]['expectMoney'] = totalAll;
            $('#zjk-saleChance-dg').datagrid('reloadFooter');*/
            //操作栏视图展示
            $("a[name='saleChance-details']").linkbutton({
                width: 40, iconCls: 'icon-my_detail', plain: true,
                onClick:function () {
                   var row = $('#zjk-saleChance-dg').datagrid('getSelected');
                   if(row){
                       $('#zjk-saleChance-details').dialog('open').panel({
                           onLoad:function () {
                               $("#zjk-saleChance-details-f").form('load',row);
                               $("#zjk-saleChance-theme").val(row.chanceTheme);//主题
                               $("#zjk-saleChance-updateDate").val(row.updateDate);//更新日期
                               $("#zjk-saleChance-client").val(row.clientId);//客户
                               $("#zjk-saleChance-state").val(row.state);
                               $("#zjk-saleChance-contact").val(row.contactId);
                               $("#zjk-saleChance-user").val(row.userId);
                               $("#zjk-saleChance-findTime").val(row.findTime);
                               $("#zjk-saleChance-outlineNeed").val(row.outlineNeed);
                               $("#zjk-saleChance-expectDate").val(row.expectDate);
                               $("#zjk-saleChance-expectMoney").val(row.expectMoney);
                               $("#zjk-saleChance-priority").val(row.priority);
                               $("#zjk-saleChance-asterisk").val(row.asterisk);
                               $("#zjk-saleChance-stage").val(row.stage);
                               $("#zjk-saleChance-stageRemain").val(row.stageRemain);
                               $("#zjk-saleChance-remarks").val(row.remarks);
                               $("#zjk-saleChance-intentRpoduct").val(row.intentRpoduct);
                               $("#zjk-saleChance-succedaneum").val(row.succedaneum);
                               $("#zjk-saleChance-type").val(row.type);
                               $("#zjk-saleChance-possbility").val(row.possibility);




                           }

                       })
                   }
                }
            });
            //操作栏删除事件
            $("a[name='saleChance-delete']").linkbutton({
                width: 40, iconCls: 'icon-my_delete', plain: true,
                onClick: function () {
                    $('#zjk-saleChance-dg').datagrid({
                        onClickCell: function (index) {
                            var rows = $('#zjk-saleChance-dg').datagrid('getRows');
                            var id = rows[index].chId;
                            $.post('deleteSaleChance', {chId: id}, function (r) {
                                if (r.success) {
                                    $.messager.alert("成功","删除成功！")
                                    $('#zjk-saleChance-dg').datagrid('reload');
                                } else {
                                    $.messager.alert("提示", r.message);
                                }
                            });
                            $('#zjk-saleChance-dg').datagrid({
                                onClickCell: function (index) {
                                }
                            });
                        }

                    });


                }
            });
            //编辑销售机会
            $("a[name='saleChance-edit']").linkbutton({
                width: 40, iconCls: 'icon-my_edit', plain: true,
                onClick : function() {
                    $("#zjk-saleChance-dg").datagrid({
                        onClickCell : function(index) {
                            var rows = $('#zjk-saleChance-dg').datagrid('getRows');// 获得所有行
                            var row = rows[index];// 根据index获得其中一行。
                            if (row) {
                                $("#zjk-edit-sale-chance").window("open").panel({
                                    onLoad : function() {
                                        $("#zjk-edit-saleChance-f").form('load', row);
                                        $("#zjk-edit-saleChance-client").combobox({
                                            url: 'saling/getClientInfoList',
                                            method: 'post',
                                            valueField: 'cid',
                                            textField: 'cname',
                                            panelHeight: 'auto',
                                            editable:false,
                                            readonly:true,
                                            onSelect: function (record) {
                                                var url = "saling/loadContactInformation";
                                                $("#zjk-edit-saleChance-contact").combobox({
                                                    url: url,
                                                    method: 'post',
                                                    panelHeight: 'auto',
                                                    queryParams: {'cid': record.cid},
                                                    valueField: 'contactid',
                                                    textField: 'contactName',
                                                });

                                            }
                                        });
                                        $("#zjk-edit-saleChance-user").combobox({
                                            url: 'saling/getUserInfoList',
                                            method: 'post',
                                            panelHeight: 'auto',
                                            valueField: 'uId',
                                            textField: 'uname',
                                            editable:false,
                                            readonly:true
                                        });

                                    }
                                });
                            }
                            $("#zjk-saleChance-dg").datagrid({
                                onClickCell : function(index) {
                                }
                            });


                        }
                    });

                }
            });

            //编辑窗口“保存”按钮事件
            $("#zjk-saleChance-add-dialog-bb-save1").linkbutton({
                onClick:function () {
                    //提交表单事件
                    $('#zjk-edit-saleChance-f').form({
                        onSubmit:function (parmps) {
                            //表单验证
                            return $(this).form('validate');
                        },
                        success:function (r) {
                            r = eval('(' + r + ')');
                            if (r.success){
                                $.messager.alert("提示","恭喜，修改成功！");
                                //窗口关闭
                                $('#zjk-edit-sale-chance').dialog('close');
                                //刷新展示列表
                                $('#zjk-saleChance-dg').datagrid('reload');

                            }else {
                                $.messager.alert("错误",r.messager);
                            }

                        }
                    }).submit();
                }
            });

        }


    });

    //从excel表格中导入销售机会信息
    $('#saleChance-tools-btn-shangchuan').linkbutton({
        onClick:function(){
            $("<div>").attr("id", "shangchuan-saleChance-result-dialog").dialog({
                width : 750,
                height : 300,
                closed : true,
                href : 'uploadExcel',
                title : '导入销售机会',
                iconCls : 'icon-save2',
                shadow : true,
                onClose : function() {
                    $(this).window("destroy");
                    $("#zjk-saleChance-dg").datagrid('reload');
                }
            });
            $("#shangchuan-saleChance-result-dialog").window("open").panel({
                onLoad:function(){
                    $('#uploadBtn').linkbutton({
                        onClick : function() {
                            var uploadEventFile = $("#uploadEventFile").filebox("getValue");
                            if (uploadEventFile == '') {
                                alert("请选择excel,再上传");
                            } else if (uploadEventFile.lastIndexOf(".xls") < 0) {//可判断以.xls和.xlsx结尾的excel
                                alert("只能上传Excel文件");
                            } else {
                                $('#uploadForm').form({
                                    url:'upload-excel-saleChance',
                                    method:'post',
                                    onSubmit : function() {
                                        return $(this).form('validate');
                                    },
                                    success : function(data) {
                                        data = eval('('+data+')');
                                        if(data.success){
                                            $.messager.alert('成功', '恭喜，成功导入销售机会！');
                                            $("#zjk-saleChance-dg").datagrid('reload');
                                            $("#shangchuan-saleChance-result-dialog").dialog("close");

                                        }else{
                                            $.messager.alert("提示", data.message);
                                        }
                                    }
                                }).submit();
                            }

                        }
                    });
                }
            });

        }
    })


    //将销售机会信息从数据库导出到excel
    $('#saleChance-tools-btn-xiazai').linkbutton({
        onClick:function(){
            var url =  'saleChance-export-excel';
            location.href = url;
        }
    });


   /* // 加载echarts组件
    // 柱状图
    simpleBar('zjk-main1');
    // renderLegend();
    // 饼状图
    renderChartBar01('zjk-main2');
    // 集群性能
    renderLayer04Right('zjk-main3');*/
})


// 动态添加操作栏图标
function format(value, row, index) {
    var str = '<a name="saleChance-details" href="#" class="easyui-linkbutton edit-btn" data-options="" title="视图"></a>' +
        '<a name="saleChance-delete" href="#" class="easyui-linkbutton edit-btn" title="删除"></a>' +
        '<a name="saleChance-edit" href="#" class="easyui-linkbutton edit-btn" title="编辑"></a>';
    return str;

}

/* 清除数据表格中的数据 */
function clearDataGrid() {
    // 获取当前页的记录数
    var item = $('#zjk-saleChance-dg').datagrid('getRows');
    if (item != null) {
        for (var i = item.length - 1; i >= 0; i--) {
            var index = $('#zjk-saleChance-dg').datagrid('getRowIndex', item[i]);
            $('#zjk-saleChance-dg').datagrid('deleteRow', index);
        }
    }

}


function formatM(value,row,index){
    if(value!=null){
        var y = String(value).indexOf(".") + 1;//获取小数点的位置
        var count = String(value).length - y;//获取小数点后的个数
        if(y > 0 && count == 1){
            return '<b style="color: #9cc8f7;">'+"￥"+value+ "0" + '</b>';
        }else if (y > 0 && count > 1){
            return '<b style="color: #9cc8f7;">'+"￥"+value+ '</b>';
        } else {
            return '<b style="color: #9cc8f7;">' + "￥" + value + ".00" + '</b>';
        }
    }else {
        return value;
    }
}

function formatM2(value,row,index){
    if(value=="70%"||value=="80%"||value=="90%"||value=="100%"){
        return '<b style="color: #3aee36;">'+value+'</b>';
    }else if(value=="40%"||value=="50%"||value=="60%"){
        return '<b style="color: orange;">'+value+'</b>';
    }else if (value=="00%"||value=="10%"||value=="20%"||value=="30%"){
        return '<b style="color: red;">'+value+'</b>';
    }else {
        return value;
    }
}
